//
//  BFMapViewController.m
//  beifang
//
//  Created by Apple on 17/4/26.
//  Copyright © 2017年 郭凯. All rights reserved.
//

#import <MapKit/MapKit.h>
#import "BFMapViewController.h"
#import "BFAnnotation.h"

@interface BFMapViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic,strong)  CLLocationManager *locationManager;
@property (nonatomic,strong) CLGeocoder* gecooder;//编码器
/**记录定位的坐标*/
@property (nonatomic,strong) NSMutableArray* locations;
@property (nonatomic,strong) MKPolyline*rountLine;
@property (nonatomic,assign) MKMapRect routeRect;
@property (nonatomic,strong) MKPolylineView* routeLineView;
@end

@implementation BFMapViewController
-(NSMutableArray *)locations{
    if (!_locations) {
        _locations = [NSMutableArray array];
    }
    return _locations;
}
-(CLGeocoder *)gecooder{
    if (!_gecooder) {
        _gecooder = [[CLGeocoder alloc]init];
    }
    return _gecooder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    /**第一步,请求用户定位授权 plist文件添加 Privacy - Location When In Use Usage Description*/
    CLLocationManager *locationManager=[[CLLocationManager alloc]init];
    self.locationManager=locationManager;
    locationManager.delegate = self;
    locationManager.distanceFilter = 1.0;
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
    
    //请求授权
    [locationManager requestWhenInUseAuthorization];
    [locationManager startUpdatingLocation];//开启定位
    /*
     MKUserTrackingModeNone  不进行用户位置跟踪
     MKUserTrackingModeFollow  跟踪用户的位置变化
     MKUserTrackingModeFollowWithHeading  跟踪用户位置和方向变化
     */
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    /*
     MKMapTypeStandard  标准地图
     MKMapTypeSatellite    卫星地图
     MKMapTypeHybrid      鸟瞰地图
     MKMapTypeSatelliteFlyover
     MKMapTypeHybridFlyover
     */
    self.mapView.mapType =  MKMapTypeStandard;
    //实时显示交通路况 默认值No
    self.mapView.showsTraffic=YES;
    //显示建筑物
    self.mapView.showsBuildings = YES;
    // 指南针 默认值 Yes
    self.mapView.showsCompass = YES;
    // 兴趣点 默认值 yes
    self.mapView.showsPointsOfInterest = YES;
    //设置显示用户显示位置 默认值就是Yes
    self.mapView.showsUserLocation = YES ;
    /**比例尺 默认值NO*/
    self.mapView.showsScale = NO;
    //设置代理
    self.mapView.delegate=self;
    
    
}


// Location Manager Delegate Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location = locations.firstObject;
    NSLog(@"纬度=%lf 经度=%lf",location.coordinate.latitude,location.coordinate.longitude);
    [manager stopUpdatingLocation];
}


#pragma mark MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    NSLog(@"区域变化");
     NSLog(@"%f,%f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta);
}


NSInteger noUpdates=0;
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    NSLog(@"更新用户位置");
    /**
     *  MKUserLocation : 专业术语: 大头针模型 其实喊什么都行, 只不过这个类遵循了大头针数据模型必须遵循的一个协议 MKAnnotation
     // title : 标注的标题
     // subtitle : 标注的子标题
     */
    userLocation.title = @"中央人民广播电视塔";
    userLocation.subtitle = @"南门外大街100号";
    
    // 移动地图的中心,显示用户的当前位置
//        [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
//     显示地图的显示区域
    
    // 控制区域中心
    CLLocationCoordinate2D center = userLocation.location.coordinate;
    
//    CLLocationCoordinate2D center = CLLocationCoordinate2DMake(39.5420, 116.23);

    //天安门
//    CLLocationCoordinate2D center = CLLocationCoordinate2DMake(39.9088966409,116.3974357338);
    // 设置区域跨度
    MKCoordinateSpan span = MKCoordinateSpanMake(0.0175042068, 0.013108986);
    
    // 创建一个区域
    MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
    // 设置地图显示区域
    [mapView setRegion:region animated:YES];
}


/**
 *  在地图上操作大头针, 就等于操作大头针数据模型
 *  添加大头针: 添加大头针数据模型
 *  删除大头针: 删除大头针数据模型
 */

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    // 要求, 鼠标点击地图的哪个位置, 就在对应的位置加一个大头针
    
    // 1. 获取当前用户在屏幕上点击的点坐标
    UITouch *touch = [touches anyObject];
    CGPoint center = [touch locationInView:self.mapView];
    // 2. 把点坐标 转换成 在地图对应的地理坐标
    CLLocationCoordinate2D centerCoordinate = [self.mapView convertPoint:center toCoordinateFromView:self.mapView];
    // 3. 设置弹框标题和子标题
    NSString *title=@"标题";
    NSString *subTitle=@"详细地址";
    // 4. 调用自定义方法, 添加大头针数据模型
    BFAnnotation *annotation = [self addAnnotationWithCoordinate:centerCoordinate title:title andSubtitle:subTitle];
    // 反地理编码
    CLLocation *location = [[CLLocation alloc] initWithLatitude:centerCoordinate.latitude longitude:centerCoordinate.longitude];
    [self.gecooder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        NSLog(@"placemarks==%@",placemarks);
        // 地标对象
        CLPlacemark *pl = [placemarks firstObject];
        // 取详细地址
        NSString *name = pl.name;
        // 获取城市
        NSString *city = pl.locality;
        annotation.title = city;
        annotation.subtitle = name;
    }];
}


-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    // 获取地图上所有的大头针数据模型
    NSArray *annotations = self.mapView.annotations;
    // 移除大头针
    [self.mapView removeAnnotations:annotations];
}

/**
 *  自定义方法,添加大头针
 *
 *  @param center   大头针扎在哪
 *  @param title    弹框标题
 *  @param subTitle 弹框子标题
 */
- (BFAnnotation *)addAnnotationWithCoordinate:(CLLocationCoordinate2D)center title:(NSString *)title andSubtitle:(NSString *)subTitle{
    BFAnnotation *annotation = [[BFAnnotation alloc] init];
    annotation.coordinate = center;
    annotation.title = title;
    annotation.subtitle = subTitle;
    // 获取地图上所有的大头针数据模型
    NSArray *annotations = self.mapView.annotations;
    // 移除大头针
    [self.mapView removeAnnotations:annotations];
    [self.mapView addAnnotation:annotation];
    return annotation;
}

/**
 *  当我们添加大头针数据模型时, 就会调用这个方法, 查找对应的大头针视图
 *
 *  @param mapView    地图
 *  @param annotation 大头针数据模型
 *
 *  @return 大头针视图
 *  注意: 如果这个方法, 没有实现, 或者, 这个方法返回nil, 那么系统就会调用系统默认的大头针视图
 */
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
    // 如果是系统的大头针数据模型, 那么使用系统默认的大头针视图,
    if([annotation isKindOfClass:[MKUserLocation class]]){
        return nil;
    }
    
    // 如果想要自定义大头针视图, 必须使用MKAnnotationView 或者 继承 MKAnnotationView 的子类
    
    // 设置循环利用标识
    static NSString *pinID = @"pinID";
    
    // 从缓存池取出大头针数据视图
    MKAnnotationView *customView = [mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
    
    // 如果取出的为nil , 那么就手动创建大头针视图
    if (customView == nil) {
        customView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
    }
    // 1. 设置大头针图片
    customView.image = [UIImage imageNamed:@"datouzhen.png"];
    // 2. 设置弹框
    customView.canShowCallout = YES;
//     2.1 设置大头针偏移量
//        customView.centerOffset = CGPointMake(100, -100);
    // 2.2 设置弹框的偏移量
    //    customView.calloutOffset = CGPointMake(100, 100);
    // 3. 自定义弹框
    // 3.1 设置弹框左侧的视图
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    imageView.image = [UIImage imageNamed:@"datouzhen.png"];
    customView.leftCalloutAccessoryView = imageView;
    // 3.2 设置弹框右侧视图
    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    imageView2.image = [UIImage imageNamed:@"datouzhen.png"];
    customView.rightCalloutAccessoryView = imageView2;
    // 3.3 设置弹框的详情视图(一定要注意,对应的版本)
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
//        customView.detailCalloutAccessoryView = [UISwitch new];
    }
    // 设置大头针视图可以被拖拽
    customView.draggable = NO;
    return customView;
}

/**
 *  选中大头针视图时调用这个方法
 *
 *  @param mapView 地图
 *  @param view    大头针视图
 */
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    NSLog(@"选中---%@", view.annotation.title);
}

@end
